package com.zx.mobile.service.proxy;

import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.SessionInfoService;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.SessionInfoModel;
import com.zx.map.utils.MyBeanUtils;
import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.domain.LoginDomain;
import com.zx.mobile.domain.MobileUserDomain;
import com.zx.platform.utils.AccountObjectSerializerUtil;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.PmpUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

public class LoginCommonProxy {

	/**
	 * 根据登录请求获取系统用户
	 * @param merchantInfoService
	 * @param loginDomain
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static List<MerchantInfoModel> getMerchantByLoginRequest(
			MerchantInfoService merchantInfoService, LoginDomain loginDomain)
			throws UnsupportedEncodingException {
		MerchantInfoModel param = new MerchantInfoModel();
		param.setSysAccount(loginDomain.getLoginAccount());
		param.setSysPassword(PmpUtils.encoderByMD5(loginDomain
				.getLoginPassword()));
		param.setProductType(MobileCommonHelper.PRODUCTTYPE_APP);// 仅查询app用户
		return merchantInfoService.getListByModel(param);
	}

	/**
	 * 将之前登录信息删除  并重新记录session信息
	 * @param user
	 * @param sessionInfoService
	 * @return
	 * @throws IOException
	 */
	public static String dealSessionInfo(String sessionId,
			MobileUserDomain user,
			SessionInfoService sessionInfoService) throws IOException {
		String loginKey = user.getMerchantInfoDetailModel().getSysAccount();
		sessionInfoService.delete(loginKey);
		//2、  然后新增登录信息保存
		SessionInfoModel sessionInfoModel = new SessionInfoModel();
		sessionInfoModel.setSessionId(sessionId);
		sessionInfoModel.setExpireDate(getSysTimeOutDate());// 1小时后失效
		sessionInfoModel.setSessionInfo(MyBeanUtils.beanToJson(user));
		sessionInfoModel.setLoginKey(loginKey);//保存主键key  用户登录手机号
		sessionInfoService.add(sessionInfoModel);
		return sessionId;	
		
	}
	
	/**
	 * 获取超时时间
	 * @return
	 */
	private static Date getSysTimeOutDate() {		
		return DateUtils.addDateByHour(
				new Date(), MobileCommonHelper.SYSLOGINTIMEOUT);
	}

}
